package com.xingfudazi.web.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xingfudazi.app.domain.*;
import com.xingfudazi.app.service.*;
import com.xingfudazi.app.service.domain.WxRequestService;
import com.xingfudazi.common.core.controller.BaseController;
import com.xingfudazi.common.core.domain.AjaxResult;
import com.xingfudazi.common.core.domain.Result;
import com.xingfudazi.common.core.page.TableDataInfo;
import com.xingfudazi.common.enums.DBDataStatus;
import com.xingfudazi.common.utils.SecurityUtils;
import com.xingfudazi.web.vo.AppActVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author YuJiaMing
 * date 2024年09月20日 00:19
 */
@RestController
@RequestMapping("/app/act")
public class AppActController extends BaseController {

    @Autowired
    private IAppActService appActService;

    @Autowired
    private IAppActSignService appActSignService;

    @Autowired
    private IAppCollectService appCollectService;

    @Autowired
    private WxRequestService wxRequestService;

    @Autowired
    private IAppAccountService appAccountService;

    @Autowired
    private IAppMemberService appMemberService;

    private boolean checkRisk(Map<String, ?> response, String content) {
        if (content == null || content.isEmpty()) {
            return false;
        }

        Integer errorCode = (Integer) response.get("errcode");
        if (errorCode == null || errorCode != 0) {
            // Handle error code not being 0 or missing
            return true; // Assuming an error is considered a risk
        }

        @SuppressWarnings("unchecked")
        List<Map<String, ?>> detail = (List<Map<String, ?>>) response.get("detail");

        if (detail == null || detail.isEmpty()) {
            // No details provided, consider as no risk
            return false;
        }

        return detail.stream()
                .filter(item -> "content_model".equals(item.get("strategy")))
                .anyMatch(item -> {
                    Object labelObj = item.get("label");
                    return labelObj instanceof Integer && ((Integer) labelObj) != 100;
                });
    }

    /**
     * 新增
     */
    @PostMapping
    public Result<?> add(@RequestBody AppAct appAct) {
        Long userId = SecurityUtils.getUserId();

        AppMember appMember = appMemberService.getById(userId);
        Long aid = appMember.getAid();
        AppAccount appAccount = appAccountService.selectAppAccountById(aid);
        String openId = appAccount.getWxOpenId();
        Map<String, ?> nameRes = (Map<String, ?>) wxRequestService.riskText(appAct.getActName(), openId);
        if (checkRisk(nameRes, appAct.getActName())) {
            return Result.fail("当前用户名 内容存在风险");
        }
        Map<String, ?> organizerRes = (Map<String, ?>) wxRequestService.riskText(appAct.getOrganizer(), openId);
        if (checkRisk(organizerRes, appAct.getOrganizer())) {
            return Result.fail("当前组织人 内容存在风险");
        }
        Map<String, ?> contentRes = (Map<String, ?>) wxRequestService.riskText(appAct.getContent(), openId);
        if (checkRisk(contentRes, appAct.getContent())) {
            return Result.fail("当前活动内容 内容存在风险");
        }
        Map<String, ?> noteRes = (Map<String, ?>) wxRequestService.riskText(appAct.getNote(), openId);
        if (checkRisk(noteRes, appAct.getNote())) {
            return Result.fail("当前注意事项 内容存在风险");
        }
        Map<String, ?> desRes = (Map<String, ?>) wxRequestService.riskText(appAct.getDes(), openId);
        if (checkRisk(desRes, appAct.getDes())) {
            return Result.fail("当前活动描述 内容存在风险");
        }

        this.appActService.save(appAct);
        return Result.success();
    }


    /**
     * 详情
     */
    @GetMapping("{id}")
    public Result<AppAct> get(@PathVariable Long id) {
        return Result.success(this.appActService.getById(id));
    }


    /**
     * 删除
     */
    @DeleteMapping("{id}")
    public Result<?> delete(@PathVariable Long id) {
        AppAct updateObj = AppAct.builder().actId(id).delFlag(DBDataStatus.DELETED.getCode()).build();
        this.appActService.updateById(updateObj);
        return Result.success();
    }


    /**
     * 查询动态列表
     */
    @GetMapping("/list")
    public Result<Page<AppActVO>> list(AppAct appAct) {
        startPage();
        List<AppAct> list = this.appActService.selectList(appAct);
        long total = getDataTable(list).getTotal();
        // 查看是否参与过活动
        Set<Long> actIds = list.stream().map(AppAct::getActId).collect(Collectors.toSet());
        LambdaQueryWrapper<AppActSign> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppActSign::getNid, SecurityUtils.getUserId());
        wrapper.in(AppActSign::getActId, actIds);
        Map<Long, AppActSign> actIdMap = this.appActSignService.list(wrapper).stream().collect(Collectors.toMap(AppActSign::getActId, Function.identity()));


        LambdaQueryWrapper<AppCollect> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(AppCollect::getNid, SecurityUtils.getUserId());
        wrapper2.in(AppCollect::getBid, actIds);
        Map<Long, AppCollect> collectMap = this.appCollectService.list(wrapper2).stream().collect(Collectors.toMap(AppCollect::getBid, Function.identity()));

        List<AppActVO> resultList = list.stream().map(item -> {
            AppActVO appActVO = new AppActVO();
            BeanUtils.copyProperties(item, appActVO);
            appActVO.setSign(actIdMap.containsKey(item.getActId()));
            appActVO.setCollect(collectMap.containsKey(item.getActId()));
            return appActVO;
        }).collect(Collectors.toList());

        Page<AppActVO> page = new Page<>();
        page.setTotal(total);
        page.setRecords(resultList);
        return Result.success(page);
    }


    /**
     * 报名
     */
    @PostMapping("sign")
    public Result<?> sing(@RequestBody AppActSign appActSign) {
        Long userId = SecurityUtils.getUserId();
        appActSign.setNid(userId);
        this.appActService.sign(appActSign);
        return Result.success();
    }


    /**
     * 报名审核
     */
    @PostMapping("sign/check")
    public Result<?> signCheck(@RequestBody AppActSign appActSign) {
        this.appActService.signCheck(appActSign);
        return Result.success();
    }


    /**
     * 查询动态列表
     */
    @GetMapping("/sign/list")
    public TableDataInfo<AppActSign> list(AppActSign appActSign) {
        startPage();
        List<AppActSign> list = this.appActSignService.selectList(appActSign);
        return getDataTable(list);
    }

}
